package github.saw96x.remoting.transport.netty.client;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 存储并获取channel
 *
 * @author Saw96x
 * @date 2022/3/18 8:52
 */
@Slf4j
public class ChannelProvider {

  private final Map<String, Channel> channelMap;

  public ChannelProvider() {
    channelMap = new ConcurrentHashMap<>();
  }

  public Channel get(InetSocketAddress inetSocketAddress) {
    String key = inetSocketAddress.toString();
    // 如果有连接有对应的地址
    if (channelMap.containsKey(key)) {
      Channel channel = channelMap.get(key);
      // if so, determine if the connection is available, and if so, get it directly
      if (channel != null && channel.isActive()) {
        return channel;
      } else {
        channelMap.remove(key);
      }
    }
    return null;
  }

  public void set(InetSocketAddress inetSocketAddress, Channel channel) {
    String key = inetSocketAddress.toString();
    channelMap.put(key, channel);
  }

  public void remove(InetSocketAddress inetSocketAddress) {
    String key = inetSocketAddress.toString();
    channelMap.remove(key);
    log.info("Channel map size :[{}]", channelMap.size());
  }
}
